import { ref, computed } from 'vue'
import { defineStore } from 'pinia'
import axios from '../utils/axios-config'

// 全局变量追踪认证状态的初始化，确保只做一次完整初始化
let globalInitDone = false;

export const useAuthStore = defineStore('auth', () => {
  // 状态
  const adminId = ref('')
  const token = ref('')
  const name = ref('')
  const role = ref('')
  const permissions = ref([])
  const isLoggedIn = computed(() => !!token.value)
  const tokenExpiration = ref(0) // 添加token过期时间跟踪
  const lastAuthCheck = ref(0) // 记录上次认证检查的时间戳

  // 初始化状态（从localStorage加载）
  function initializeStore() {
    console.log('[认证Store] 开始初始化认证状态...');
    
    const storedToken = localStorage.getItem('admin_token')
    const storedAdminId = localStorage.getItem('admin_id')
    const storedName = localStorage.getItem('admin_name')
    const storedRole = localStorage.getItem('admin_role')
    const storedPermissions = localStorage.getItem('admin_permissions')

    console.log('[认证Store] localStorage token状态:', storedToken ? '存在' : '不存在');

    if (storedToken) {
      // 更新状态前确保变更
      if (token.value !== storedToken) {
        console.log('[认证Store] 从localStorage更新token状态');
        token.value = storedToken
      }
      
      adminId.value = storedAdminId || ''
      name.value = storedName || ''
      role.value = storedRole || ''
      
      try {
        permissions.value = storedPermissions ? JSON.parse(storedPermissions) : []
      } catch (error) {
        console.error('[认证Store] 解析permissions失败:', error);
        permissions.value = [];
      }
      
      console.log('[认证Store] 认证状态已初始化, isLoggedIn:', isLoggedIn.value);
      
      // 全局标记设为已初始化
      globalInitDone = true;
    } else {
      console.log('[认证Store] localStorage中无token，确保store状态为未登录');
      // 确保清除所有状态
      logout();
    }
    
    return isLoggedIn.value;
  }

  // 确保认证状态是最新的，增加缓存策略，防止频繁检查
  async function checkAndRefreshAuth() {
    console.log('[认证Store] 检查认证状态同步...');
    
    const now = Date.now();
    const checkThreshold = 2000; // 两秒内不重复检查认证状态
    
    // 如果最近刚检查过，且已经完成过初始化，直接返回当前状态以提高性能
    if (globalInitDone && now - lastAuthCheck.value < checkThreshold) {
      console.log('[认证Store] 最近已检查过认证状态，跳过重复检查');
      return isLoggedIn.value;
    }
    
    // 更新最后检查时间
    lastAuthCheck.value = now;
    
    try {
      // 重新从localStorage读取token，确保在不同组件间状态同步
      const storedToken = localStorage.getItem('admin_token')
      const storedExpiration = localStorage.getItem('admin_token_expiration')
      
      // 快速返回未登录状态（避免不必要的操作）
      if (!storedToken) {
        console.log('[认证Store] localStorage中无token，确认未登录状态');
        if (isLoggedIn.value) {
          console.log('[认证Store] store中仍有登录状态，清除');
          logout();
        }
        return false;
      }
      
      // 确保store中的token和localStorage一致
      if (storedToken && (!token.value || token.value !== storedToken)) {
        console.log('[认证Store] 从localStorage恢复/更新认证状态');
        initializeStore();
      }
      
      // 检查token是否即将到期并尝试刷新
      if (storedExpiration) {
        const expirationTime = parseInt(storedExpiration, 10)
        const currentTime = Math.floor(Date.now() / 1000)
        const timeRemaining = expirationTime - currentTime
        
        console.log(`[认证Store] Token有效期: 还剩${timeRemaining}秒`);
        
        // 如果token距离过期不到5分钟，尝试刷新token
        if (timeRemaining < 300 && timeRemaining > 0) {
          console.log(`[认证Store] Token将在${timeRemaining}秒后过期，尝试刷新...`);
          try {
            await refreshToken();
            console.log('[认证Store] Token刷新完成，当前登录状态:', isLoggedIn.value);
          } catch (error) {
            console.error('[认证Store] Token刷新失败:', error);
          }
        } else if (timeRemaining <= 0) {
          console.log('[认证Store] Token已过期，执行登出');
          logout();
        }
      }
      
      // 确认并返回最终登录状态
      console.log('[认证Store] 认证检查完毕，最终登录状态:', isLoggedIn.value);
      return isLoggedIn.value;
    } catch (error) {
      console.error('[认证Store] 认证状态检查发生错误:', error);
      // 出错时保守处理，保持现有状态不变
      return isLoggedIn.value;
    }
  }

  // 刷新token方法
  async function refreshToken() {
    try {
      console.log('[认证Store] 尝试刷新token...');
      const response = await axios.post('/admin/refresh-token')
      
      if (response.data.error === 0) {
        // 刷新成功，更新token
        const userData = response.data.body
        token.value = userData.token
        
        // 更新localStorage中的token和过期时间
        localStorage.setItem('admin_token', userData.token)
        if (userData.expiresAt) {
          tokenExpiration.value = userData.expiresAt
          localStorage.setItem('admin_token_expiration', userData.expiresAt.toString())
        }
        
        console.log('[认证Store] Token刷新成功');
        return true;
      } else {
        console.warn('[认证Store] 刷新token失败:', response.data.message);
        return false;
      }
    } catch (error) {
      console.error('[认证Store] 刷新token出错:', error);
      if (error.response && error.response.status === 401) {
        // 刷新失败，清除登录状态
        logout();
      }
      return false;
    }
  }

  // 登录方法
  async function login(username, password) {
    try {
      const response = await axios.post('/admin/login', {
        username,
        password
      })

      if (response.data.error === 0) {
        // 登录成功，保存数据
        const userData = response.data.body
        adminId.value = userData.adminId
        token.value = userData.token
        name.value = userData.name
        role.value = userData.role
        permissions.value = userData.permissions

        // 保存到localStorage
        localStorage.setItem('admin_token', userData.token)
        localStorage.setItem('admin_id', userData.adminId)
        localStorage.setItem('admin_name', userData.name)
        localStorage.setItem('admin_role', userData.role)
        localStorage.setItem('admin_permissions', JSON.stringify(userData.permissions))
        
        // 设置全局初始化标记
        globalInitDone = true;
        console.log('[认证Store] 登录成功，认证状态已更新');

        // token已通过axios拦截器自动添加到请求头

        return { success: true, message: response.data.message }
      } else {
        return { success: false, message: response.data.message }
      }
    } catch (error) {
      console.error('[认证Store] 登录失败:', error);
      return { 
        success: false, 
        message: error.response?.data?.message || '登录失败，请检查网络连接'
      }
    }
  }

  // 登出方法
  function logout() {
    console.log('[认证Store] 执行登出操作，清除认证状态');
    
    // 清除状态
    adminId.value = ''
    token.value = ''
    name.value = ''
    role.value = ''
    permissions.value = []

    // 清除localStorage
    localStorage.removeItem('admin_token')
    localStorage.removeItem('admin_id')
    localStorage.removeItem('admin_name')
    localStorage.removeItem('admin_role')
    localStorage.removeItem('admin_permissions')
    
    // 重置全局标记
    globalInitDone = false;

    // token会通过axios拦截器处理
  }

  // 检查是否有特定权限
  function hasPermission(permissionName) {
    if (!permissionName || permissionName === '') return true
    return permissions.value.includes(permissionName)
  }

  // 初始化store
  if (!globalInitDone) {
    initializeStore()
  }

  return { 
    adminId, 
    token, 
    name, 
    role, 
    permissions, 
    isLoggedIn,
    tokenExpiration,
    login,
    logout,
    hasPermission,
    checkAndRefreshAuth,
    refreshToken,
    initializeStore
  }
})